<?php
/**
 * Created by jinqiang on 2024/6/20 17:51.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;




use App\Http\Models\Mysql\NnyyUserTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseTable;
use App\Http\Models\Mysql\SsyProcessingListTable;

class OmsRepository
{
    //推送加工单信息到巨益 奇门
    public static function push($processingCode)
    {
        $processingList = (new SsyProcessingListTable())->where('processing_code', $processingCode)->get()->toArray();
        $user = (new NnyyUserTable())->where('name', $processingList[0]['order_processor'])->first();
        if(empty($user)){
            return ['code' => -1, 'msg' => '推送失败：用户表未发现该理单员信息'];
        }
        $subjects = array_column(config('scm.subject'), null, 'brand_code_s');
        list($orderLines, $ownercode, $warehousecode) = [[], "", ""];
        foreach ($processingList as $item){
            $ownercode = $subjects[$item['brand_code']]['owner_code'] ?? "";
            $warehousecode = $subjects[$item['brand_code']]['warehouse_code'] ?? "";
            $orderLines[] = [
                'outBizCode' => $item['processing_code'], //外部业务编码
                'orderLineNo' => $item['id'], //入库单的行号
                'ownerCode' => $ownercode, //货主编码
                'itemCode' => $item['sku_code'], //商品编码
                'itemId' => $item['processing_code'], //仓储系统商品ID
                'itemName' => $item['type_name'], //商品名称
                //'planQty' => $item['num']+ceil($item['num']*0.05), //应收商品数量 2023-09-17 龙安提出要溢出数
                'planQty' => $item['num'], //修改于20230517  龙安提出不要溢出数   2024-01-10 龙安提出不推溢出数
                'skuProperty' => $item['processing_code'], //商品属性
                'purchasePrice' => $item['unit_price'], //采购价
                'actualPrice' => $item['unit_price'], //采购价
                'retailPrice' => $item['unit_price'], //零售价
                'inventoryType' => 'ZP', //库存类型(ZP=正品;CC=残次;JS=机损;XS=箱损;默认为ZP)
                'produceCode' => '00001', //生产批号
                'batchCode' => '00001', //批次编码
                'unit' => '件', // 单位
                'snList' => ['sn'=>'asfdsf'] // 单位
            ];
        }
        $data = [
            'orderLines' => $orderLines,
            'entryOrder' => [
                'entryOrderCode' => $processingCode, //入库单号
                'ownerCode' => $ownercode,//货主编码
                'purchaseOrderCode' => "",//$processingList[0]['po_id'],//采购单号
                'warehouseCode' => $warehousecode,//入库仓库编码
                'orderCreateTime' => $processingList[0]['add_date'],//订单创建时间
                'orderType' => 'CGRK',//业务类型(SCRK=生产入库,LYRK=领用入库,CCRK=残次品入库,CGRK=采购入库,DBRK=调拨入库,QTRK=其他入库,B2BRK=B2B入 库,XNRK=虚拟入库,只传英文编码)
                'relatedOrders' => ['orderType'=>"CG",'orderCode'=>"G1234"],
                'expectStartTime' => $processingList[0]['production_date'],//预期到货时间
                'expectEndTime' => $processingList[0]['contract_date'],//最迟预期到货时间
                'logisticsCode' => 'OTHER',//物流公司编码(SF=顺丰、EMS=标准快递、EYB=经济快件、ZJS=宅急送、YTO=圆通 、ZTO=中通(ZTO)、HTKY=百世汇通、 UC=优速、STO=申通、TTKDEX=天天快递、QFKD=全峰、FAST=快捷、POSTB=邮政小包、GTO=国通、YUNDA=韵达、JD=京东配送、DD=当当宅配、 AMAZON=亚马逊物流、OTHER=其他(只传英文编码))
                'logisticsName' => '测试物流名称',//物流公司名称
                'expressCode' => 'dd123456',//运单号
                'supplierCode' => $processingList[0]['supplier_id'],//供应商编码
                'supplierName' => $processingList[0]['factory_name'],//供应商名称
                'operatorCode' => $user->id,//操作员编码
                'operatorName' => $user->name,//操作员名称
                'operateTime' => date('Y-m-d H:i:s'),
                'remark' => preg_match("/^FC/", $processingCode) ? "【返修-备注】" : "",
                'totalOrderLines' => count($processingList) ,//加工单数量
                //'warehouseName' => '入库仓库名称',//入库仓库名称
                //'sourceWarehouseCode' => '出库仓库编码',//出库仓库编码
                //'sourceWarehouseName' => '出库仓库名称',//出库仓库名称
            ]
        ];
        //发送curl 请求
        $url='http://114.55.253.204/shisanyu/qimen/entryOrderCreate';
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return [json_decode($resp, true), $data];
    }

    //手动完结巨益采购通知单
    public static function end($processingCode)
    {
        $processingList = (new SsyProcessingListTable())->where('processing_code', $processingCode)->get()->toArray();
        $subjects = array_column(config('scm.subject'), null, 'brand_code_s');
        $pnoRes = self::endPNO($processingList, $subjects);
        $poRes = self::endPO($processingList[0]);
        return [
            'code' => $poRes['success'] == true && $pnoRes['success'] == true ? 0 : -1,
            'msg' => $poRes['success'] == true && $pnoRes['success'] == true ? "操作成功" : (
                $poRes['success'] == true ? "采购通知单完结失败" : ($pnoRes['success'] == true ? "采购单完结失败": "采购单、采购通知单均失败"))
        ];
    }

    //完结采购通知单
    public static function endPNO($processingList, $subjects)
    {
        list($orderLines, $ownercode, $warehousecode) = [[], "", ""];
        foreach ($processingList as $item){
            $ownercode = $subjects[$item['brand_code']]['owner_code'] ?? "";
            $warehousecode = $subjects[$item['brand_code']]['warehouse_code'] ?? "";
            $orderLines[] = [
                'actualQty' => 0,
                'inventoryType' => 'ZP', //库存类型(ZP=正品;CC=残次;JS=机损;XS=箱损;默认为ZP)
                'itemCode' => $item['sku_code'], //商品编码
                'itemId' => $item['processing_code'], //仓储系统商品ID
                'ownerCode' => $ownercode, //货主编码
                'orderLineNo' => $item['id'], //入库单的行号
            ];
        }
        $data = [
            'orderLines' => $orderLines,
            'entryOrder' => [
                'status' => 'PARTFULFILLED',
                'confirmType' => 0,
                'ownerCode' => $ownercode,//货主编码
                'warehouseCode' => $warehousecode,//入库仓库编码
                'entryOrderCode' => $processingList[0]['jy_purchase_number'] ?? "", //采购通知单
                'entryOrderType' => 'CGRK',
                'operateTime' => date('Y-m-d H:i:s'),
                //'outBizCode' => $processingList[0]['jy_number'] ?? "",
                //'entryOrderId' => $processingList[0]['jy_number'] ?? "",
                'remark' => "",
            ]
        ];
        $secret='ssy-scm'; //安全码
        $param = array(                      // 按接口提供的逐一填写
            "format"         => 'json',
            "appKey"        => 'ssy-scm',
            "sign_method"    => 'md5',
            "customerId"     => 'ssy-scm',
        );
        // 交给奇门
        $method           = "entryorder.confirm";
        $body             = json_encode($data, JSON_UNESCAPED_UNICODE);
        $param['method']    = $method;
        $param['timestamp'] = date("Y-m-d H:i:s");
        $param['sign']      = self::sign($secret, $param, $body);   //利用body签名
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $body,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($body)]
        ];
        $resp = httpCurl($url, $form);
        return json_decode($resp,true);
    }

    //完结采购单
    public static function endPO($processingObj)
    {
        $data = [
            'entryOrderCode' => $processingObj['processing_code'],
            'orderCode' => $processingObj['jy_number'] ?? "",
            'status' => 4
        ];
        $secret='ssy-scm'; //安全码
        $param = array(                      // 按接口提供的逐一填写
            "format"         => 'json',
            "appKey"        => 'ssy-scm',
            "sign_method"    => 'md5',
            "customerId"     => 'ssy-scm',
        );
        // 交给奇门
        $method           = "order.finish.confirm";
        $body             = json_encode($data, JSON_UNESCAPED_UNICODE);
        $param['method']    = $method;
        $param['timestamp'] = date("Y-m-d H:i:s");
        $param['sign']      = self::sign($secret, $param, $body);   //利用body签名
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $body,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($body)]
        ];
        $resp = httpCurl($url, $form);
        return json_decode($resp,true);
    }

    //取消加工单计划任务 奇门
    public static function cancel($processingCode)
    {
        $processingObj = (new SsyProcessingListTable())->where('processing_code', $processingCode)->first();
        $subjects = array_column(config("scm.subject"), null, 'brand_code_s');
        $warehousecode = $subjects[$processingObj->brand_code]['warehouse_code'];
        $data = [
            "warehouseCode" => $warehousecode,
            "ownerCode" => "",
            "orderCode" => $processingCode,
            "orderId" => "",
            "orderType" => 'CGRK',
            "cancelReason" => "",
            "extendProps" => "",
            "subSourceOrders" => [['subSourceOrderCode' => ""]],
        ];
        $url='http://114.55.253.204/shisanyu/qimen/orderCancel';
        $data= json_encode($data,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $data,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)]
        ];
        $resp = httpCurl($url, $param);
        return [json_decode($resp, true), $data];
    }

    //推送调拨单据--内购
    public static function pushAllocation($ipurchaseObj)
    {
        $allocationNumber = $ipurchaseObj['allocation_number'];
        $ipurchaseOrders = (new SsyAllocationIpurchaseTable())->where('allocation_number', $allocationNumber)->get()->toArray();
        $details = [];
        foreach ($ipurchaseOrders as $item){
            $details[] = [
                'actualPrice' => round((Double)$item['price'] * (Double)$ipurchaseObj['discount'], 2),
                'itemCode' => $item['sku_code'],
                'planQty' => $item['num'],
                'retailPrice' => (Double)$item['price']
            ];
        }
        $data = [
            'deliveryOrder' => [
                'createTime' => $ipurchaseObj['createtime'],
                'deliveryOrderCode' => $ipurchaseObj['allocation_number'],
                'operateTime' => $ipurchaseObj['createtime'],
                'orderType' => 'JYCK',
                'placeOrderTime' => $ipurchaseObj['createtime'],
                'receiverInfo' => [
                    "city" => $ipurchaseObj['wp_city'],
                    "detailAddress" => $ipurchaseObj['wp_address'],
                    "mobile" => $ipurchaseObj['wp_phone'],
                    "name" => $ipurchaseObj['wp_user'],
                    "province" => $ipurchaseObj['wp_province'],
                    "area" => $ipurchaseObj['wp_area'],
                ],
                'shopCode' => 'SSYKZNG01',
                'shopNick' => '内购'
            ],
            'orderLines' => $details
        ];
        $secret='ssy-scm'; //安全码
        $param = array(                      // 按接口提供的逐一填写
            "format"         => 'json',
            "appKey"        => 'ssy-scm',
            "sign_method"    => 'md5',
            "customerId"     => 'ssy-scm',
        );
        // 交给奇门
        $method           = "deliveryorder.create";
        $body             = json_encode($data, JSON_UNESCAPED_UNICODE);
        $param['method']    = $method;
        $param['timestamp'] = date("Y-m-d H:i:s");                               //时间
        $param['sign']      = self::sign($secret, $param, $body);   //利用body签名
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $body,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($body)]
        ];
        $resp = httpCurl($url, $form);
        $res= json_decode($resp,true);
        $isPush = $res['success'] === true ? 1 : 2;
        (new SsyAllocationIpurchaseListTable())->updateDataWhere(['allocation_number' => $allocationNumber], ['is_push' => $isPush]);
        return $isPush == 1 ? ['code' => 0, 'msg' => '推送调拨计划成功', 'data' => $res] : ['code' => -1, 'msg' => '推送调拨计划失败', 'data' => $res];
    }

    //创建采退返修出库单 奇门
    public static function stickout($data, $processingMap, $remark = "")
    {
        $subjects = array_column(config("scm.subject"), null, 'brand_code_s');
        list($ownercode, $warehousecode, $orderLines, $processingObj) = ["", "", [], $processingMap[$data[0]['sku_code']]];
        foreach ($data as $item){
            $brandCode = $processingMap[$item['sku_code']]['brand_code'];
            $ownercode = $subjects[$brandCode]['owner_code'] ?? "";//货主编码
            $warehousecode = $subjects[$brandCode]['warehouse_code'] ?? "";//仓库编码
            $orderLines[] = [
                'outBizCode' => $item['processing_code'], //外部业务编码
                'orderLineNo' => $processingMap[$item['sku_code']]['id'], //入库单的行号
                'ownerCode' => $ownercode, //货主编码
                'itemCode' => $item['sku_code'], //商品编码
                'itemId' => $item['processing_code'], //仓储系统商品ID
                'inventoryType' => 'ZP', //库存类型(ZP=正品;CC=残次;JS=机损;XS= 箱损;ZT=在途库存;默认为查所有类型的库存)
                'itemName' => $item['type_name'], //商品名称
                'planQty' => intval($item['num']), //应收商品数量
                'batchCode' => '001', //批次编码
                'productDate' => '2022-07-17', //	生产日期(YYYY-MM-DD)
                'expireDate' => '2022-07-17', //过期日期(YYYY-MM-DD)
                'produceCode' => '001',//生产批号
                'platformCode' => '0011',//	交易平台商品编码
                'unit' => '件',//单位
                'skuProperty' => $item['processing_code'], //商品属性
                'purchasePrice' => $processingMap[$item['sku_code']]['unit_price'], //采购价
                'retailPrice' => $processingMap[$item['sku_code']]['unit_price'], //零售价
                'actualPrice' => $processingMap[$item['sku_code']]['unit_price'], //零售价
                'inventoryType' => 'ZP' //库存类型(ZP=正品;CC=残次;JS=机损;XS=箱损;默认为ZP)
            ];
        }
        $pickerInfo=array("company"=>'提货人公司','name'=>'姓名',"tel"=>'81020340','mobile'=>'13214567869',"id"=>'476543213245733','carNo'=>'浙A0001');//提货人信息
        $senderInfo=array('company'=>'测试发件人公司名称','name'=>'姓名','81020340'=>'邮编','tel'=>'81020340','mobile'=>'13214567869','email'=>'电子邮箱','countryCode'=>'国家二字码','province'=>'省份','city'=>'城市','area'=>'区域','town'=>'村镇','detailAddress'=>'详细地址','id'=>'476543213245733');
        $receiverInfo=array('company'=>'测试收件人公司名称','name'=>'姓名','81020340'=>'邮编','tel'=>'81020340','mobile'=>'13214567869','email'=>'电子邮箱','countryCode'=>'国家二字码','province'=>'省份','city'=>'城市','area'=>'区域','town'=>'村镇','detailAddress'=>'详细地址','id'=>'476543213245733');
        $pushData = [
            'orderLines' => $orderLines,
            'deliveryOrder' => [
                'totalOrderLines' => count($data), //单据总行数
                //'deliveryOrderCode' => $ssy_processing_lists['processing_code'];//出库单号
                'deliveryOrderCode' => date("YmdHis"),//出库单号
                'orderType' => "CGTH",//出库单类型
                'relatedOrders' => [['orderType'=>'CG','orderCode'=>$processingObj['processing_code']]],//关联单据信息
                'warehouseCode' => $warehousecode,//仓库编码
                'createTime' => "2022-07-17 18:00:01",//出库单创建时间(YYYY-MM-DD HH:MM:SS)
                'scheduleDate' => "2022-07-17",//要求出库时间(YYYY-MM-DD)
                'logisticsCode' => '',
                'logisticsName' => '',
                'supplierCode' => $processingObj['supplier_id'],
                'supplierName' => $processingObj['factory_name'],
                'transportMode' => '自提',
                'pickerInfo' => $pickerInfo,
                'senderInfo' => $senderInfo,
                'receiverInfo' => $receiverInfo,
                'remark' => $remark,
                'orderSourceType' => '',
                'receivingTime' => date("Y-m-d H:i:s"),
                'shippingTime' => date("Y-m-d H:i:s")
            ]
        ];
        //发送curl 请求
        $url='http://114.55.253.204/shisanyu/qimen/stockoutCreate';
        $pushData= json_encode($pushData,JSON_UNESCAPED_UNICODE);
        $param = [
            'json' => $pushData,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($pushData)]
        ];
        $resp = httpCurl($url, $param);
        return [json_decode($resp, true), $pushData];
    }

    //推送加工厂
    public static function pushFactory($factoryObj)
    {
        $secret='ssy-scm'; //安全码
        $param = array(                      // 按接口提供的逐一填写
            "format"         => 'json',
            "appKey"        => 'ssy-scm',
            "sign_method"    => 'md5',
            "customerId"     => 'ssy-scm',
        );
        // 交给奇门
        $method           = "supplier.synchronize";
        $body             = json_encode([
            'actionType' => 'add',
            'supplierCode' => $factoryObj['supplier_id'],
            'supplierName' => $factoryObj['factory_name'],
            'name' => $factoryObj['legal_person'] ?? "",
            'tel' => $factoryObj['contact_phone'] ?? "",
            'detailAddress' => $factoryObj['contact_address'] ?? "",
            'isValid' => 'Y',
            'remark' => $factoryObj['remark'] ?? ""
        ]);
        $param['method']    = $method;
        $param['timestamp'] = date("Y-m-d H:i:s");                               //时间
        $param['sign']      = self::sign($secret, $param, $body);   //利用body签名
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $body,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($body)]
        ];
        $resp = httpCurl($url, $form);
        return [json_decode($resp, true), $body];
    }

    //查询库存、可销数
    public static function searchNum($virtualWarehouseCode, $productCodes)
    {
        $secret='ssy-scm'; //安全码
        $param = array(                      // 按接口提供的逐一填写
            "format"         => 'json',
            "appKey"        => 'ssy-scm',
            "sign_method"    => 'md5',
            "customerId"     => 'ssy-scm',
        );
        // 交给奇门
        $method           = "greatonce.oms.stock.list";
        $body             = json_encode(["virtualWarehouseCode" => $virtualWarehouseCode, "skuCodeLists" => $productCodes]);      // 创建BODY
        $param['method']    = $method;                                         // 此处填写要应对应BODY，
        $param['timestamp'] = date("Y-m-d H:i:s");                               //时间
        $param['sign']      = self::sign($secret, $param, $body);   //利用body签名
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $body,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($body)]
        ];
        $res = httpCurl($url, $form);
        return json_decode($res, true);
    }

    //商品信息
    public static function searchItem($page = 1, $limit = 20, $skuCodes = [], $productCodes = [])
    {
        $input = '{"skuCodes": []}';
        if(!empty($skuCodes)){
            $input = json_encode(["skuCodes" => $skuCodes]);
        }elseif(!empty($productCodes)){
            $input = json_encode(['productCodes' => $productCodes]);
        }
        $secret='ssy-scm'; //安全码
        $param = [
            "format"       => 'json',
            "appKey"       => 'ssy-scm',
            "sign_method"  => 'md5',
            "customerId"   => 'ssy-scm',
            "page"         => $page,
            "pageSize"     => $limit,
            "method"       => "items.query",
            "timestamp"    => date('Y-m-d H:i:s')
        ];
        $param['sign'] = self::sign($secret, $param, $input);   //利用body签名
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $input,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($input)]
        ];
        $resp = httpCurl($url, $form);
        return json_decode($resp,true);
    }

    //组合商品查询
    public static function searchCombineItem($page = 1, $limit = 20, $skuCode = "")
    {
        $input = [];
        if(!empty($skuCode)){
            $input = json_encode(["skuCode" => $skuCode]);
        }
        $secret='ssy-scm'; //安全码
        $param = [
            "format"       => 'json',
            "appKey"       => 'ssy-scm',
            "sign_method"  => 'md5',
            "customerId"   => 'ssy-scm',
            "page"         => $page,
            "pageSize"     => $limit,
            "method"       => "combineitem.query",
            "timestamp"    => date('Y-m-d H:i:s')
        ];
        $param['sign'] = self::sign($secret, $param, $input);   //利用body签名
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $input,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($input)]
        ];
        $resp = httpCurl($url, $form);
        return json_decode($resp,true);
    }

    //获取采购通知单
    public static function searchPno($fromCode)
    {
        $input = json_encode(["fromCode" => $fromCode]);
        $secret = 'ssy-scm'; //安全码
        $param = [
            "format" => 'json',
            "appKey" => 'ssy-scm',
            "sign_method" => 'md5',
            "customerId" => 'ssy-scm',
            "method" => "oms.purchasenoticeorder.query",
            "timestamp" => date("Y-m-d H:i:s"),
            "pageSize" => 100
        ];
        $param['sign'] = self::sign($secret, $param, $input);
        $url = "https://www.jeoms.com/shisanyu/api/api/api.do?".http_build_query($param);
        $form = [
            "json" => $input,
            'headers' => ['Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($input)]
        ];
        $resp = httpCurl($url, $form);
        return json_decode($resp,true);
    }

    /** * 签名*/
    public static function sign($secret, $param, $body) {
        if ( empty($body) ) {
            exit('Body can\'t empty!');
        }
        if ( empty($secret) ) {
            exit('Secret error!');
        }
        ksort($param);
        $outputStr = '';
        foreach ($param as $k => &$v) {
            if ( empty($v) ) {
                exit('Param can\'t error!');
            }
            $outputStr .= $k . $v;
        }
        $outputStr = $secret . $outputStr . $body . $secret;
        return strtoupper(md5($outputStr));
    }
}
